package com.mall.utils;

import com.mall.common.core.utils.LocalDateTimeUtils;
import com.mall.common.security.framework.aware.ApplicationUtils;
import com.mall.project.sys.cons.ScheduleCons;
import com.mall.project.sys.model.entity.QuartzJob;
import com.mall.project.sys.model.parm.QuartzJobLogPARM;
import com.mall.project.sys.service.IQuartzJobLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.BeanUtils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 抽象quartz调用
 */
@Slf4j
public abstract class AbstractQuartzJob implements Job {

    /**
     * 线程本地变量
     */
    private static ThreadLocal<LocalDateTime> threadLocal = new ThreadLocal<>();

    @Override
    public void execute(JobExecutionContext context) {
        QuartzJob quartzJob = new QuartzJob();
        BeanUtils.copyProperties(context.getMergedJobDataMap().get(ScheduleCons.TASK_PROPERTIES), quartzJob);
        try {
            before(context, quartzJob);
            if (quartzJob != null) {
                doExecute(context, quartzJob);
            }
            after(context, quartzJob, null);
        } catch (Exception e) {
            log.error("任务执行异常", e);
            after(context, quartzJob, e);
        }
    }

    /**
     * 执行前
     *
     * @param context   工作执行上下文对象
     * @param quartzJob 系统计划任务
     */
    protected void before(JobExecutionContext context, QuartzJob quartzJob) {
        threadLocal.set(LocalDateTime.now());
    }

    /**
     * 执行后
     *
     * @param context   工作执行上下文对象
     * @param quartzJob 系统计划任务
     */
    protected void after(JobExecutionContext context, QuartzJob quartzJob, Exception e) {
        LocalDateTime startTime = threadLocal.get();
        threadLocal.remove();

        final QuartzJobLogPARM logPARM = new QuartzJobLogPARM();
        logPARM.setJobName(quartzJob.getJobName());
        logPARM.setJobGroup(quartzJob.getJobGroup());
        logPARM.setInvokeTarget(quartzJob.getInvokeTarget());
        logPARM.setStartTime(startTime);
        logPARM.setEndTime(LocalDateTime.now());
        long runMs = LocalDateTimeUtils.betweenTwoTime(logPARM.getStartTime(), logPARM.getEndTime(), ChronoUnit.MILLIS);
        logPARM.setJobMessage(logPARM.getJobName() + " 总共耗时：" + runMs + "毫秒");
        if (e != null) {
            logPARM.setStatus(1);
            String errorMsg = StringUtils.substring(getExceptionMessage(e), 0, 2000);
            logPARM.setExceptionInfo(errorMsg);
        } else {
            logPARM.setStatus(0);
        }

        // 写入数据库当中
        ApplicationUtils.getBean(IQuartzJobLogService.class).addJobLog(logPARM);
    }

    /**
     * 执行方法，由子类重载
     *
     * @param context   工作执行上下文对象
     * @param quartzJob 系统计划任务
     * @throws Exception 执行过程中的异常
     */
    protected abstract void doExecute(JobExecutionContext context, QuartzJob quartzJob) throws Exception;


    /**
     * 获取exception的详细错误信息。
     */
    public static String getExceptionMessage(Throwable e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        String str = sw.toString();
        return str;
    }
}
